<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2022/7/7
 * Time: 17:03
 * redis 锁
 */

namespace app\index\controller;


use think\cache\driver\Redis;

class Lock
{
    private static $_instance ;
    private   $_redis;
    private function __construct()
    {
        $this->_redis =  new Redis();
        $this->_redis ->connect('127.0.0.1');
    }

    public static function getInstance()
    {
        if(self::$_instance instanceof self)
        {
            return self::$_instance;
        }
        return self::$_instance = new  self();
    }


    /**
     * @function 加锁
     * @param $key 锁名称
     * @param $expTime 过期时间
     * @return bool
     */
    public function set($key,$expTime)
    {
        //初步加锁
        $isLock = $this->_redis->setnx($key,time()+$expTime);
        if($isLock)
        {
            return true;
        }
        else
        {
            //加锁失败的情况下。判断锁是否已经存在，如果锁存在切已经过期，那么删除锁。进行重新加锁
            $val = $this->_redis->get($key);
            if($val&&$val<time())
            {
                $this->del($key);
                return  $this->_redis->setnx($key,time()+$expTime);
            }
            return false;
        }
    }

    /**
     * @param $key 解锁
     */
    public function del($key)
    {
        $this->_redis->del($key);
    }



}